import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import tkinter.messagebox as messagebox
from PIL import Image, ImageTk
import pytesseract
import re


class ImageToTextApp:
    def __init__(self, root):
        self.root = root
        self.root.title("图像文字识别器")
        self.root.geometry("800x600")
        self.root.configure(bg='#1e1e1e')

        # 创建主框架
        self.main_frame = tk.Frame(root, bg='#1e1e1e')
        self.main_frame.pack(expand=True, fill='both', padx=20, pady=20)

        # 创建选择区域
        self.drop_frame = tk.Frame(self.main_frame, bg='#2d2d2d', width=600, height=300)
        self.drop_frame.pack(pady=20)
        self.drop_frame.pack_propagate(False)

        # 提示标签
        self.drop_label = tk.Label(self.drop_frame,
                                   text="点击此处选择图片",
                                   bg='#2d2d2d', fg='#ffffff',
                                   font=('Arial', 14))
        self.drop_label.pack(expand=True)

        # 选择图片按钮
        self.select_button = ttk.Button(self.main_frame,
                                        text="选择图片",
                                        command=self.select_file,
                                        style='Accent.TButton')
        self.select_button.pack(pady=10)

        # 识别按钮
        self.scan_button = ttk.Button(self.main_frame,
                                      text="开始识别",
                                      command=self.scan_image,
                                      style='Accent.TButton')
        self.scan_button.pack(pady=10)

        # 结果显示区域
        self.result_text = tk.Text(self.main_frame,
                                   height=10,
                                   bg='#2d2d2d',
                                   fg='#ffffff',
                                   font=('Consolas', 12))
        self.result_text.pack(fill='both', expand=True)

        # 点击选择文件
        self.drop_frame.bind('<Button-1>', lambda e: self.select_file())

        self.image_path = None

    def select_file(self, event=None):
        self.image_path = filedialog.askopenfilename(
            filetypes=[("Image files", "*.png *.jpg *.jpeg *.bmp *.gif")])
        if self.image_path:
            self.show_preview(self.image_path)

    def show_preview(self, image_path):
        try:
            # 显示预览图
            image = Image.open(image_path)
            image = image.resize((580, 280), Image.Resampling.LANCZOS)
            photo = ImageTk.PhotoImage(image)

            if hasattr(self, 'preview_label'):
                self.preview_label.destroy()

            self.preview_label = tk.Label(self.drop_frame, image=photo, bg='#2d2d2d')
            self.preview_label.image = photo
            self.preview_label.pack(expand=True)
            self.drop_label.pack_forget()
        except Exception as e:
            messagebox.showerror("错误", f"无法加载图片: {str(e)}")

    def scan_image(self):
        if not self.image_path:
            messagebox.showwarning("警告", "请先选择一张图片")
            return

        try:
            image = Image.open(self.image_path)
            text = pytesseract.image_to_string(image, lang='chi_sim')

            # 显示结果
            self.result_text.delete(1.0, tk.END)
            self.result_text.insert(tk.END, f"识别结果:\n{text}")

        except Exception as e:
            messagebox.showerror("错误", f"识别失败: {str(e)}")


# 主程序入口
if __name__ == "__main__":
    root = tk.Tk()
    app = ImageToTextApp(root)
    root.mainloop()